from django import forms
from app01 import models
import hashlib
from django.core.exceptions import ValidationError
from django.forms.models import MultipleHiddenInput
class Bsform(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if isinstance(field,(MultipleHiddenInput,forms.BooleanField,models.MultiSelectField)):
                continue
            field.widget.attrs['class'] = 'form-control'



class Payment_operation(Bsform):
    '''
    缴费表
    '''
    class Meta:
        model=models.PaymentRecord
        fields = '__all__'

class Enroll_operation(Bsform):
    '''
    报名表
    '''
    class Meta:
        model=models.Enrollment
        fields='__all__'
    def __init__(self,*args,**kwargs):
        super(Enroll_operation,self).__init__(*args,**kwargs)
        # customer_obj = models.Customer.objects.get(pk=customer_id)
        # self.fields['customer'].choices=[(customer_id,customer_obj)]
        # self.fields['enrolment_class'].choices=[(i.pk,str(i)) for i in customer_obj.class_list.all()]
        self.fields['customer'].choices = [(self.instance.customer_id, self.instance.customer)]
        self.fields['enrolment_class'].choices = [(i.pk, str(i)) for i in self.instance.customer.class_list.all()]


class Consult_operation(Bsform):
    '''
    跟进记录
    '''
    class Meta:
        model = models.ConsultRecord
        fields = '__all__'
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['customer'].choices=models.Customer.objects.filter(consultant=request.user_obj).values_list('id','name')
        self.fields['consultant'].choices=[(request.user_obj.pk,request.user_obj)]
class Customer_operation(forms.ModelForm):
    '''
    增加和编辑客户
    '''

    class Meta:
        model = models.Customer
        fields = '__all__'


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if isinstance(field, (MultipleHiddenInput, forms.BooleanField, models.MultiSelectField)):
                continue
            field.widget.attrs['class'] = 'form-control'

        self.fields['course'].widget.attrs['class'] = ''


class Register(forms.ModelForm):
    re_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '确认密码'}))

    class Meta:
        model = models.UserProfile
        fields = "__all__"
        exclude = ['is_active']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = '用户名'
        self.fields['name'].widget.attrs['placeholder'] = '姓名'
        self.fields['mobile'].widget.attrs['placeholder'] = '手机号'
        self.fields['password'].widget = forms.PasswordInput(attrs={'placeholder': '密码'})
        self.fields['department'].choices = [('', '请选择部门')] + list(models.Department.objects.values_list('id', 'name'))

    def clean(self):
        self._validate_unique = True
        password = self.cleaned_data.get('password', '')
        re_password = self.cleaned_data.get('re_password')
        if password == re_password:
            md5 = hashlib.md5()
            md5.update(password.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()
            return self.cleaned_data
        self.add_error('re_password', '两次密码不一致')
        raise ValidationError('两次密码不一致')



class Classlist_operation(Bsform):
    '''
    班级表
    '''
    class Meta:
        model = models.ClassList
        fields = '__all__'


class Course_operation(Bsform):
    '''
    课程记录
    '''
    class Meta:
        model = models.CourseRecord
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print(self.instance)
        self.fields['re_class'].choices = [(self.instance.re_class_id, self.instance.re_class)]
        self.fields['recorder'].choices = [(self.instance.recorder_id, self.instance.recorder)]


class Student_operation(Bsform):
    '''
    学习记录
    '''
    class Meta:
        model = models.StudyRecord
        fields = '__all__'